package com.qna;

import java.io.File;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.qna.pojo.Question;

@Controller
public class StartController {

	@RequestMapping("/startq")
	public String HelloController(final Model model, final Principal principal) {
		String desktop = System.getProperty ("user.home") + "/Desktop/yo/";
		String userDetailsFolder = "/userdetails/";

		Question question = new Question();
		List<String[]> resultsForView = new ArrayList<String[]>();
		File[] filesForQuestions = new File(desktop).listFiles();

		UserDetails userDetails = new UserDetails();
		File[] userDetailsFiles = new File(desktop+userDetailsFolder).listFiles();
		Boolean isExistingAttempts = false;
		for (File tempFile : userDetailsFiles) {
			if (tempFile.isFile() && tempFile.getName().contains("xml")) {
				if(tempFile.getName().equalsIgnoreCase(principal.getName().concat(".xml"))){
					isExistingAttempts = true;
				}
			}
		}
		File userDetailFile = new File(desktop+userDetailsFolder+principal.getName()+".xml");
		for (File file : filesForQuestions) {
			if (file.isFile() && file.getName().contains("xml")) {
				String[] temp = new String[3];
				temp[0] = file.getName();

				File tempFile = new File(desktop+"/"+file.getName());
				JAXBContext jaxbContext;
				try {
					jaxbContext = JAXBContext.newInstance(Question.class);

					Unmarshaller u;

					u = jaxbContext.createUnmarshaller();
					question = (Question)u.unmarshal(tempFile);
				} catch (JAXBException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (question.getSubmittedBy().equalsIgnoreCase(principal.getName())) {
					temp[1] = "y";

				}
				else{
					temp[1] = "n";
				}
				if(isExistingAttempts){
					try {
						jaxbContext = JAXBContext.newInstance(UserDetails.class);
						Unmarshaller userDetailsUn = jaxbContext.createUnmarshaller();
						userDetails = (UserDetails)userDetailsUn.unmarshal(userDetailFile);
						ArrayList<Integer> questionList = userDetails.getAnsweredQuestionList();

						for (Integer i: questionList){
							if(	question.getTimestamp() == i){
								temp[2] = "y";
							}
						}
					} catch (JAXBException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
				resultsForView.add(temp);
			}

		}
		model.addAttribute("message", resultsForView);			   
		return "startq";
	}
}

